﻿using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc.Rendering;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using Webdiyer.AspNetCore;
using ZhongKeSite.Common;
using ZhongKeSite.Common.Helper;
using ZhongKeSite.Entity;
using ZhongKeSite.Entity.Models;
using ZhongKeSite.Repository;

namespace ZhongKeSite.Service
{
    public class SysService : ISysService
    {
        ISysRoleRepository sysRoleRepository;
        ISysUserRepository sysUserRepository;
        ISysRightRepository sysRightRepository;
        ISysRoleRightRepository sysRoleRightRepository;
        ISysLoginLockRepository sysLoginLockRepository;
        ISysLoginSessionRepository sysLoginSessionRepository;
        ISysDictCodeRepository sysDictCodeRepository;
        public SysService(ISysRoleRepository _sysRoleRepository,
            ISysUserRepository _sysUserRepository,
            ISysRightRepository _sysRightRepository,
            ISysLoginLockRepository _sysLoginLockRepository,
            ISysLoginSessionRepository _sysLoginSessionRepository,
            ISysRoleRightRepository _sysRoleRightRepository,
            ISysDictCodeRepository _sysDictCodeRepository)
        {
            sysRoleRepository = _sysRoleRepository;
            sysUserRepository = _sysUserRepository;
            sysRightRepository = _sysRightRepository;
            sysLoginLockRepository = _sysLoginLockRepository;
            sysLoginSessionRepository = _sysLoginSessionRepository;
            sysRoleRightRepository = _sysRoleRightRepository;
            sysDictCodeRepository = _sysDictCodeRepository;
        }

        #region 用户管理
        /// <summary>
        /// 获取
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public SysUser GetSysUser(string id)
        {
            return sysUserRepository.GetById(id);
        }
        /// <summary>
        /// 登录
        /// </summary>
        /// <returns></returns>
        public SysUser GetSysUser(string userName, string pwd)
        {
            return sysUserRepository.GetByExpression(s => s.Login == userName && s.Pwd == pwd);
        }
        /// <summary>
        /// 新增
        /// </summary>
        /// <param name="entity"></param>
        public ResultResponse AddSysUser(SysUser model)
        {
            ResultResponse response = new ResultResponse() { success = false, msg = CommonConst.Fail };
            if (string.IsNullOrWhiteSpace(model.Login) || string.IsNullOrWhiteSpace(model.Pwd))
            {
                response.msg = "用户名、密码或角色不能为空!";
                return response;
            }
            model.Name = model.Login;
            model.Pwd = EncryptionHelper.SHA1(model.Pwd);
            model.AddDate = DateTime.Now;
            model.ID = IdentityCreator.NextIdentity;
            model.IsAvailable = 1;
            model.IsDel = 0;
            response.success = sysUserRepository.Add(model);
            response.msg = response.success ? CommonConst.Success : CommonConst.Fail;
            return response;
        }
        /// <summary>
        /// 启用，停用 操作
        /// </summary>
        /// <param name="ids"></param>
        /// <param name="dateStatus"></param>
        /// <returns></returns>
        public ResultResponse UpdateSysUserState(List<string> ids, string userName, DataStatus dataStatus)
        {
            ResultResponse response = new ResultResponse() { success = false, msg = CommonConst.Fail };
            var sysUsers = sysUserRepository.GetList(s => ids.Contains(s.ID)).ToList();
            if (sysUsers != null && sysUsers.Count > 0)
            {
                switch (dataStatus)
                {
                    case DataStatus.UnAvailable:
                    case DataStatus.IsAvailable:
                        sysUsers.ForEach(k =>
                        {
                            k.IsAvailable = DataStatus.IsAvailable == dataStatus ? 1 : 0;
                            k.UpdateBy = userName;
                            k.UpdateDate = DateTime.Now;
                        });
                        response.success = sysUserRepository.Update(sysUsers);
                        break;
                    case DataStatus.Deleted:
                        response.success = sysUserRepository.Delete(sysUsers);
                        break;
                }

                response.msg = response.success ? CommonConst.Success : CommonConst.Fail;
            }
            return response;
        }
        /// <summary>
        /// 编辑
        /// </summary>
        /// <param name="entity"></param>
        public ResultResponse UpdateSysUser(SysUser model)
        {
            ResultResponse response = new ResultResponse() { success = false, msg = CommonConst.Fail };
            if (string.IsNullOrWhiteSpace(model.RoleId))
            {
                response.msg = "角色不能为空!";
                return response;
            }
            SysUser o = sysUserRepository.GetById(model.ID);
            if (o != null)
            {
                if (!model.Login.Equals(o.Login))
                {
                    var user = sysUserRepository.GetByExpression(s => s.Login == model.Login);
                    if (user != null)
                    {
                        response.msg = "用户名已经存在，请重新修改.";
                        return response;
                    }
                    o.Login = model.Login;
                }
                o.Pwd = string.IsNullOrWhiteSpace(model.Pwd) ? o.Pwd : EncryptionHelper.SHA1(model.Pwd);
                o.RoleId = model.RoleId;
                o.IsAvailable = model.IsAvailable;
                o.UpdateBy = model.UpdateBy;
                o.UpdateDate = DateTime.Now;
                response.success = sysUserRepository.Update(o);
                response.msg = response.success ? CommonConst.Success : CommonConst.Fail;
                return response;
            }
            else
            {
                response.msg = "用户不存在！";
                return response;
            }
        }
        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="id"></param>
        public ResultResponse DeleteSysUser(string id)
        {
            ResultResponse response = new ResultResponse() { success = false, msg = CommonConst.Fail };
            response.success = sysUserRepository.Delete(id);
            response.msg = response.success ? CommonConst.Success : CommonConst.Fail;
            return response;
        }
        /// <summary>
        /// 获取分页数据
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public LayPager<SysUser> GetSysUserPagedList(int pageIndex, int pageSize, string search)
        {
            Expression<Func<SysUser, bool>> predicate = k => k.IsDel == 0;
            if (!string.IsNullOrWhiteSpace(search))
            {
                search = search.Trim();
                predicate = predicate.And(s => s.Login.Contains(search));
            }
            var list = sysUserRepository.GetPagedList(pageIndex, pageSize, predicate);

            #region SysRole 赋值
            if (list != null && list.Any())
            {
                var data = list.Where(s => s.SysRole != null);
                if (!data.Any())
                {
                    List<SysRole> roleList = sysRoleRepository.GetList().ToList();
                    if (roleList != null && roleList.Any())
                    {
                        list.ForEach(s =>
                        {
                            s.SysRole = roleList.FirstOrDefault(k => k.ID == s.RoleId);
                        });
                    }
                }
            }
            #endregion

            LayPager<SysUser> pmodel = new LayPager<SysUser>();
            if (list != null)
            {
                pmodel.count = list.TotalItemCount;
                pmodel.msg = CommonConst.Success;
                pmodel.data = list.ToList();
            }
            return pmodel;
        }
        #endregion

        #region 角色管理
        /// <summary>
        /// 获取角色
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public SysRole GetSysRole(string id)
        {
            return sysRoleRepository.GetById(id);
        }

        /// <summary>
        /// 新增
        /// </summary>
        /// <param name="entity"></param>
        public ResultResponse AddSysRole(SysRole model)
        {
            ResultResponse response = new ResultResponse() { success = false, msg = CommonConst.Fail };
            if (string.IsNullOrWhiteSpace(model.RoleName))
            {
                response.msg = "角色名称不能为空!";
                return response;
            }
            var role = sysRoleRepository.GetById(model.ID);
            if (role != null)
            {
                response.msg = "角色编号已经存在，请不要重复添加.";
                return response;
            }
            var parentRole = sysRoleRepository.GetById(model.ParentID);
            if (parentRole != null)
            {
                model.RoleLevel = parentRole.RoleLevel + 1;
            }
            else
            {
                model.RoleLevel = 0;
            }
            model.HomePage = "/";
            model.SysDefined = 1;
            model.IsAvailable = 1;
            model.IsDel = 0;
            model.AddDate = DateTime.Now;

            response.success = sysRoleRepository.Add(model);
            response.msg = response.success ? CommonConst.Success : CommonConst.Fail;
            return response;
        }

        /// <summary>
        /// 获取权限树
        /// </summary>
        /// <param name="id"></param>
        /// <param name="spread"></param>
        /// <returns></returns>
        public List<Dynatree> GetRoleRightsTree(string id)
        {
            List<Dynatree> treelist = new List<Dynatree>();
            try
            {
                //默认展开
                bool spread = true;
                if (!string.IsNullOrWhiteSpace(id))
                {
                    SysRole model = GetSysRole(id);

                    var all = model == null || model.ParentID == CommonConst.Root ? sysRightRepository.GetSysRightList() : sysRightRepository.GetSysRightListByRoleId(model.ParentID);

                    var q = sysRightRepository.GetSysRightListByRoleId(id).Select(a => a.ID);
                    //五层树数据
                    treelist = all.Where(a => a.ParentCode == CommonConst.Root).OrderBy(k => k.SortNo).Select(
                        b => new Dynatree
                        {
                            id = b.ID,
                            title = b.RightName,
                            select = !all.Any(s => s.ParentCode == b.ID) && q.Contains(b.ID),
                            spread = spread,
                            children = all.Where(s => s.ParentCode == b.ID).OrderBy(k => k.SortNo).Select(
                                c => new Dynatree
                                {
                                    id = c.ID,
                                    title = c.RightName,
                                    select = !all.Any(s => s.ParentCode == c.ID) && q.Contains(c.ID),
                                    spread = spread,
                                    children = all.Where(s => s.ParentCode == c.ID).OrderBy(k => k.SortNo).Select(
                                        d => new Dynatree
                                        {
                                            id = d.ID,
                                            title = d.RightName,
                                            select = !all.Any(s => s.ParentCode == d.ID) && q.Contains(d.ID),
                                            spread = spread,
                                            children = all.Where(s => s.ParentCode == d.ID).OrderBy(k => k.SortNo).Select(
                                                f => new Dynatree
                                                {
                                                    id = f.ID,
                                                    title = f.RightName,
                                                    select = !all.Any(s => s.ParentCode == f.ID) && q.Contains(f.ID),
                                                    spread = spread,
                                                    children = all.Where(s => s.ParentCode == f.ID).OrderBy(k => k.SortNo).Select(
                                                    g => new Dynatree
                                                    {
                                                        id = g.ID,
                                                        title = g.RightName,
                                                        select = q.Contains(g.ID),
                                                        spread = spread,
                                                    }).ToList()
                                                }).ToList()
                                        }).ToList()
                                }).ToList()
                        }).ToList();

                }
            }
            catch (Exception ex)
            {
                LogHelper.Error(ex);
            }
            return treelist;
        }
        /// <summary>
        /// 角色权限设置
        /// </summary>
        /// <param name="model"></param>
        /// <param name="userName"></param>
        /// <returns></returns>
        public ResultResponse<bool> RoleSetup(SettingRequest model, CurrentUser cuser)
        {
            ResultResponse<bool> response = new ResultResponse<bool>() { success = false, msg = CommonConst.Fail };
            string roleCode = model.id;
            if (sysRoleRightRepository.Delete(k => k.RoleCode == roleCode) && model.treeList != null && model.treeList.Count > 0)
            {
                List<string> rightIds = new List<string>();
                GetRightIds(model.treeList, ref rightIds);
                List<SysRoleRight> sysRoleRights = new List<SysRoleRight>();
                foreach (string rightId in rightIds)
                {
                    sysRoleRights.Add(new SysRoleRight
                    {
                        ID = IdentityCreator.NextIdentity,
                        RoleCode = roleCode,
                        RightCode = rightId.Trim(),
                        UpdateBy = cuser.Login,
                        UpdateDate = DateTime.Now
                    });
                }
                sysRoleRightRepository.Add(sysRoleRights);
            }
            CacheHelper.Remove(CommonConst.CacheSysRight + roleCode);
            response.success = true;
            response.msg = CommonConst.Success;
            response.data = cuser.RoleId.Equals(roleCode);
            return response;
        }
        /// <summary>
        /// 编辑
        /// </summary>
        /// <param name="entity"></param>
        public ResultResponse UpdateSysRole(SysRole model)
        {
            ResultResponse response = new ResultResponse() { success = false, msg = CommonConst.Fail };
            if (string.IsNullOrWhiteSpace(model.RoleName))
            {
                response.msg = "角色名称不能为空!";
                return response;
            }
            var o = sysRoleRepository.GetById(model.ID);

            if (!o.ParentID.Equals(model.ParentID))
            {
                o.ParentID = model.ParentID;
                var parentRole = sysRoleRepository.GetById(model.ParentID);
                if (parentRole != null)
                {
                    o.RoleLevel = parentRole.RoleLevel + 1;
                }
            }
            o.RoleName = model.RoleName;
            o.SortNo = model.SortNo;
            o.UpdateBy = model.UpdateBy;
            o.UpdateDate = DateTime.Now;

            response.success = sysRoleRepository.Update(o);
            response.msg = response.success ? CommonConst.Success : CommonConst.Fail;
            return response;
        }
        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="id"></param>
        public ResultResponse DeleteSysRole(string id)
        {
            ResultResponse response = new ResultResponse() { success = false, msg = CommonConst.Fail };
            if (string.IsNullOrWhiteSpace(id))
            {
                response.msg = "角色编号不能为空!";
                return response;
            }
            response.success = sysRoleRightRepository.Delete(s => s.RoleCode == id) && sysRoleRepository.Delete(id);
            response.msg = response.success ? CommonConst.Success : CommonConst.Fail;
            return response;
        }
        /// <summary>
        /// 获取角色所有数据
        /// </summary>
        /// <returns></returns>
        public IEnumerable<SysRole> GetSysRoleList()
        {
            return sysRoleRepository.GetList(s => s.IsDel == 0).OrderBy(k => k.SortNo);
        }
        /// <summary>
        /// 获取当前登录用户的角色列表
        /// </summary>
        /// <returns></returns>
        public IEnumerable<SelectListItem> GetSysRoleListDLL()
        {
            List<SelectListItem> rolelist = new List<SelectListItem>();
            IEnumerable<SysRole> list = GetSysRoleList();
            if (list != null && list.Any())
            {
                rolelist = list.Select(p => new SelectListItem()
                {
                    Value = p.ID,
                    Text = p.RoleName
                }).ToList();
            }
            return rolelist;
        }
        /// <summary>
        /// 获取角色分页数据
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public LayPager<SysRole> GetSysRolePagedList(int pageIndex, int pageSize)
        {
            Expression<Func<SysRole, bool>> predicate = s => s.IsDel == 0;
            PagedList<SysRole> list = sysRoleRepository.GetPagedList(pageIndex, pageSize, predicate);
            LayPager<SysRole> pmodel = new LayPager<SysRole>();
            if (list != null)
            {
                pmodel.count = list.TotalItemCount;
                pmodel.msg = CommonConst.Success;
                pmodel.data = list.ToList();
            }
            return pmodel;
        }
        /// <summary>
        /// 角色下拉列表
        /// </summary>
        /// <param name="nid"></param>
        /// <returns></returns>
        public List<SelectListItem> GetSysRoleDLL(string roleId)
        {
            var all = sysRoleRepository.GetList().ToList();
            int minLevel = all.Min(a => a.RoleLevel).Value;
            List<SelectListItem> list = new List<SelectListItem>();
            all.Where(a => a.RoleLevel == minLevel).ToList().ForEach(s =>
            {
                if (s.ID != roleId)
                {
                    list.Add(new SelectListItem { Text = s.RoleName, Value = s.ID.ToString() });
                    list.AddRange(Recurrent_Sys_RoleSelect(all, s.ID, roleId));
                }
            });
            return list;
        }
        public List<SelectListItem> Recurrent_Sys_RoleSelect(IList<SysRole> all, string parentId, string croleId)
        {
            List<SelectListItem> list = new List<SelectListItem>();
            all.Where(a => a.ParentID == parentId).OrderBy(b => b.SortNo).ToList().ForEach(s =>
            {
                if (s.ID != croleId)
                {
                    string pstr = string.Empty;
                    for (int i = 0; i < s.RoleLevel; i++)
                    {
                        pstr += "　";
                    }
                    list.Add(new SelectListItem { Text = pstr + s.RoleName, Value = s.ID.ToString() });
                    list.AddRange(Recurrent_Sys_RoleSelect(all, s.ID, croleId));
                }
            });
            return list;
        }
        private void GetSys_RolesForEach(IList<SysRole> all, ref List<SysRole> list, List<SysRole> l)
        {
            foreach (var o in l)
            {
                list.Add(o);
                var k = all.Where(a => a.ParentID == o.ID).OrderBy(b => b.SortNo).ToList();
                if (k.Count > 0)
                {
                    GetSys_RolesForEach(all, ref list, k);
                }
            }
        }
        #endregion

        #region 权限管理
        /// <summary>
        /// 根据用户角色id获取用户操作权限列表
        /// </summary>
        /// <param name="roleId">角色</param>
        /// <returns></returns>
        public List<SysRight> GetSysRightListByRoleId(string roleId, Expression<Func<SysRight, bool>> other = null)
        {
            var rightList = CacheHelper.Get<List<SysRight>>(CommonConst.CacheSysRight + roleId);
            if (rightList == null)
            {
                rightList = sysRightRepository.GetList(a => a.SysRoleRight.Any(b => b.RoleCode == roleId) && a.IsAvailable == 1 && a.IsDel == 0).ToList();
                CacheHelper.Set(CommonConst.CacheSysRight + roleId, rightList, CommonConst.RightListExpire);
            }
            //特殊约束
            if (other != null)
            {
                var ep = other.Compile();
                rightList = rightList.Where(ep).ToList();
            }
            return rightList;
        }
        /// <summary>
        /// 获取权限值
        /// </summary>
        /// <returns></returns>
        public IList<SysRight> GetSysRightList()
        {
            return sysRightRepository.GetList(s => s.IsAvailable == 1 && s.IsDel == 0).ToList();
        }
        /// <summary>
        /// 获取
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public SysRight GetSysRight(string id)
        {
            return sysRightRepository.GetById(id);
        }
        /// <summary>
        /// 操作类型
        /// </summary>
        /// <param name="ParentID"></param>
        /// <param name="isInclude"></param>
        /// <param name="isValue"></param>
        /// <param name="otherItem"></param>
        /// <returns></returns>
        public List<SelectListItem> GetSysDictCodeDLL(string ParentID, bool isInclude = false, bool isValue = false, SelectListItem otherItem = null)
        {
            var q = new List<SelectListItem>();
            q = sysDictCodeRepository.GetList(a => a.ParentID == ParentID && a.IsAvailable == 1 && a.IsDel == 0).
                OrderBy(b => b.SortNo).Select(s => new SelectListItem() { Value = (isValue ? s.DictValue : s.ID), Text = s.DictName }).ToList();
            if (isInclude)
            {
                q.ForEach(s => s.Text = "　" + s.Text);
                if (ParentID == CommonConst.Root)
                {
                    q.Insert(0, new SelectListItem { Value = CommonConst.Root, Text = "默认" });
                }
                else
                {
                    var m = sysDictCodeRepository.GetByExpression(a => a.ID == ParentID);
                    if (m != null)
                    {
                        q.Insert(0, new SelectListItem { Value = m.ID, Text = m.DictName });
                    }
                }
            }
            if (otherItem != null)
            {
                q.Insert(0, otherItem);
            }
            return q;
        }
        /// <summary>
        /// 新增
        /// </summary>
        /// <param name="entity"></param>
        public ResultResponse AddSysRight(SysRight model)
        {
            ResultResponse response = new ResultResponse() { success = false, msg = CommonConst.Fail };
            var right = sysRightRepository.GetById(model.ID);
            if (right != null)
            {
                response.msg = "权限ID已经存在,请勿重复添加.";
                return response;
            }
            if (string.IsNullOrWhiteSpace(model.ParentCode))
            {
                model.ParentCode = CommonConst.Root;
                model.LevelCount = 1;
            }
            else
            {
                var o = sysRightRepository.GetById(model.ParentCode);
                if (o != null)
                {
                    model.LevelCount = o.LevelCount + 1;
                }
            }
            model.AddBy = model.AddBy;
            model.AddDate = DateTime.Now;
            model.IsAvailable = 1;
            model.IsDel = 0;
            response.success = sysRightRepository.Add(model);
            response.msg = response.success ? CommonConst.Success : CommonConst.Fail;
            return response;
        }
        /// <summary>
        /// 编辑
        /// </summary>
        /// <param name="entity"></param>
        public ResultResponse UpdateSysRight(SysRight model)
        {
            ResultResponse response = new ResultResponse() { success = false, msg = CommonConst.Fail };
            var o = sysRightRepository.GetById(model.ID);
            if (o != null)
            {
                o.RightName = model.RightName;
                o.DisplayName = model.DisplayName;
                o.IsControl = model.IsControl;
                o.IsTableControl = model.IsTableControl;
                o.IsMenu = model.IsMenu;
                o.MenuUrl = model.MenuUrl;
                o.SortNo = model.SortNo;
                o.ActionType = model.ActionType;
                o.SubSystem = model.SubSystem;
                o.Pic = model.Pic;
                o.UpdateBy = model.UpdateBy;
                o.UpdateDate = DateTime.Now;
                response.success = sysRightRepository.Update(o);
                if (response.success)
                {
                    CacheHelper.RemoveAll(CommonConst.CacheSysRight);
                }
            }
            response.msg = response.success ? CommonConst.Success : CommonConst.Fail;
            return response;
        }
        /// <summary>
        /// 编辑
        /// </summary>
        /// <param name="id"></param>
        public ResultResponse DeleteSysRight(string id)
        {
            ResultResponse response = new ResultResponse() { success = false, msg = CommonConst.Fail };
            response.success = sysRoleRightRepository.Delete(s => s.RightCode == id) && sysRightRepository.Delete(id);
            response.msg = response.success ? CommonConst.Success : CommonConst.Fail;
            return response;
        }
        /// <summary>
        /// 遍历得到所有节点id
        /// </summary>
        /// <param name="list"></param>
        /// <returns></returns>
        public List<string> GetRightIds(List<Dynatree> list, ref List<string> rightIds)
        {
            if (list != null && list.Any())
            {
                foreach (Dynatree item in list)
                {
                    rightIds.Add(item.id);
                    GetRightIds(item.children, ref rightIds);
                }
            }
            return rightIds;
        }
        /// <summary>
        /// 获取所有权限数据
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public IEnumerable<SysRight> GetAllSysRightList()
        {
            return sysRightRepository.GetList();
        }
        #endregion

        #region 登录操作
        /// <summary>
        /// 登录操作
        /// </summary>
        /// <param name="http"></param>
        /// <param name="username"></param>
        /// <param name="pwd"></param>
        /// <returns></returns>
        public ResultResponse<CurrentUser> SignIn(HttpContext httpContext, string username, string password, string vercode)
        {
            ResultResponse<CurrentUser> response = new ResultResponse<CurrentUser>() { success = false, msg = CommonConst.Fail };
            if (string.IsNullOrWhiteSpace(username) || string.IsNullOrWhiteSpace(password))
            {
                response.msg = "用户名或密码不能为空";
                return response;
            }
            if (string.IsNullOrWhiteSpace(vercode))
            {
                response.msg = "请输入验证码";
                return response;
            }
            string verifyCode = httpContext.GetCookieValue(AppSettings.LoginVerifyCookieName);
            verifyCode = EncryptionHelper.TDES(EncryptionHelper.CType.decrypt, verifyCode, AppSettings.VerifyCodeSecret);
            if (!verifyCode.EqualsIgnoreCase(vercode))
            {
                response.msg = "验证码不正确";
                return response;
            }
            username = username.Trim();
            //判断登录是否需要锁定
            string ip = httpContext.GetIP();
            SysLoginLock loginLock = sysLoginLockRepository.GetByExpression(s => s.Login == username || s.IP == ip);
            if (loginLock != null && loginLock.LastLoginDate > DateTime.Now.Date
                && loginLock.LoginCount >= AppSettings.LoginErrorLimitCount)
            {
                response.msg = string.Format("登录账号或当前登录IP错误次数已达到上限{0}次,请明天再试.", AppSettings.LoginErrorLimitCount);
                return response;
            }
            password = EncryptionHelper.SHA1(password);
            var cuser = SignIn(username, password, ip);
            if (cuser != null)
            {
                //删除验证码Cookies
                httpContext.DeleteCookie(AppSettings.LoginVerifyCookieName);
                //每次登陆清楚权限缓存，读取最新权限结构
                CacheHelper.Remove(CommonConst.CacheSysRight + cuser.RoleId);
                #region 登录成功将锁定表错误次数清0
                if (loginLock != null)
                {
                    loginLock.Login = username;
                    loginLock.IP = ip;
                    loginLock.LastLoginDate = DateTime.Now;
                    loginLock.LoginCount = 0;
                    loginLock.TotalLoginCount += 1;
                    sysLoginLockRepository.Update(loginLock);
                }
                #endregion
                response.success = true;
                response.msg = CommonConst.Success;
                response.data = cuser;
                return response;
            }
            else
            {
                #region 操作登录锁定表，不存在新增，存在更新
                if (loginLock == null)
                {
                    loginLock = new SysLoginLock();
                    loginLock.ID = IdentityCreator.NextIdentity;
                    loginLock.Login = username;
                    loginLock.IP = ip;
                    loginLock.LastLoginDate = DateTime.Now;
                    loginLock.LoginCount = 1;
                    loginLock.TotalLoginCount = 1;
                    sysLoginLockRepository.Add(loginLock);
                }
                else
                {
                    //更新
                    loginLock.Login = username;
                    loginLock.IP = ip;
                    loginLock.LastLoginDate = DateTime.Now;
                    loginLock.LoginCount += 1;
                    loginLock.TotalLoginCount += 1;
                    sysLoginLockRepository.Update(loginLock);
                }
                #endregion
                response.msg = "账号或密码不正确，请重试";
                return response;
            }
        }
        /// <summary>
        /// 登录操作
        /// </summary>
        /// <param name="http"></param>
        /// <param name="username"></param>
        /// <param name="pwd"></param>
        /// <returns></returns>
        private CurrentUser SignIn(string username, string pwd, string ip)
        {
            //查询数据库
            var user = sysUserRepository.GetByExpression(s => s.Login == username && s.Pwd == pwd && s.IsAvailable == 1 && s.IsDel == 0);
            if (user != null)
            {
                SysLoginSession ls = sysLoginSessionRepository.GetByExpression(s => s.UID == user.ID);
                if (ls == null)
                {
                    ls = new SysLoginSession();
                    ls.ID = IdentityCreator.NextIdentity;
                    ls.SID = ip;
                    ls.LoginCount = 1;
                    ls.UID = user.ID;
                    ls.FirstLoginTime = DateTime.Now;
                    ls.LastLoginTime = DateTime.Now;
                    ls.LoginDate = DateTime.Now;
                    sysLoginSessionRepository.Add(ls);
                }
                else
                {
                    ls.SID = ip;
                    ls.LastLoginTime = ls.LoginDate;
                    ls.LoginDate = DateTime.Now;
                    ls.LoginCount = ls.LoginCount.HasValue ? ls.LoginCount.Value + 1 : 1;
                    sysLoginSessionRepository.Update(ls);
                }
                CurrentUser cuser = new CurrentUser(user, ls);
                return cuser;
            }
            return null;
        }
        /// <summary>
        /// 获取当前登录用户信息
        /// </summary>
        /// <param name="httpContext"></param>
        /// <param name="authenticationScheme"></param>
        /// <returns></returns>
        public CurrentUser GetCurrentUser(HttpContext httpContext, string authenticationScheme)
        {
            CurrentUser cuser = new CurrentUser();
            var authenticate = httpContext.AuthenticateAsync(authenticationScheme);
            if (authenticate != null && authenticate.Result.Succeeded)
            {
                //默认
                //var claimIdentity = (ClaimsIdentity)httpContext.User.Identity;

                var claimIdentity = authenticate.Result.Principal.Claims.ToList();
                if (claimIdentity.FirstOrDefault(s => s.Type == CommonConst.UserID) != null)
                {
                    cuser.UserID = claimIdentity.FirstOrDefault(s => s.Type == CommonConst.UserID).Value;
                }
                if (claimIdentity.FirstOrDefault(s => s.Type == CommonConst.Login) != null)
                {
                    cuser.Login = claimIdentity.FirstOrDefault(s => s.Type == CommonConst.Login).Value;
                }
                if (claimIdentity.FirstOrDefault(s => s.Type == CommonConst.UserName) != null)
                {
                    cuser.UserName = claimIdentity.FirstOrDefault(s => s.Type == CommonConst.UserName).Value;
                }
                if (claimIdentity.FirstOrDefault(s => s.Type == CommonConst.RoleId) != null)
                {
                    cuser.RoleId = claimIdentity.FirstOrDefault(s => s.Type == CommonConst.RoleId).Value;
                }
                if (claimIdentity.FirstOrDefault(s => s.Type == CommonConst.LoginCount) != null)
                {
                    string loginCountStr = claimIdentity.FirstOrDefault(s => s.Type == CommonConst.LoginCount).Value;
                    cuser.LoginCount = Convert.ToInt32(loginCountStr);
                }
                if (claimIdentity.FirstOrDefault(s => s.Type == CommonConst.LastLoginDate) != null)
                {
                    string loginDateStr = claimIdentity.FirstOrDefault(s => s.Type == CommonConst.LastLoginDate).Value;
                    cuser.LastLoginDate = Convert.ToDateTime(loginDateStr);
                }
            }
            return cuser;
        }
        #endregion
        
    }
}
